const express = require('express')
const common = require('../../libs/common')
const mysql = require('mysql')
const db = mysql.createPool({
	host: 'localhost',
	user: 'root',
	password: 'root',
	database: 'learn',
})

module.exports = function(){
	let router = express.Router()
	router.get('/',(req,res) => {

		switch(req.query.act){
			case 'del':
				db.query(`delete from banner_table WHERE ID='${req.query.id}'`,(err,data)=>{
					if(err){
						res.status(500).send('database err').end()
					}else{
						res.redirect('/admin/banner')
					}
				})
			break;
			case 'change':
				db.query(`select * from banner_table where ID='${req.query.id}'`,(err,data)=>{
					if(err){
						console.error(err)
						res.status(500).send('database err').end()
					}else if(data.length == 0){
						res.status(404).send('data.length == 0').end()
					}else{

						db.query(`select * from banner_table`,(err,banners)=>{
							if(err){
								res.status(500).send('database err').end()
							}else{
								res.render('admin/banner.ejs',{banners,change_data: data[0]})
							}
						})
					}
				})
			break;
			default:
				db.query(`select * from banner_table`,(err,banners)=>{
				if(err){
					res.status(500).send('database err').end()
				}else{
					res.render('admin/banner.ejs',{banners})
				}
			})
			break;
		}
		
	})
	router.post('/',(req,res) => {

		let title = req.body.title;
		let description = req.body.description;
		let href = req.body.href;
		if(!title || !description || !href){
			res.status(400).send('数据不能为空').end()
		}else{


			if(req.body.change_id){
				db.query(`update banner_table set title='${req.body.title}', 
					description='${req.body.description}', href='${req.body.href}' 
					where ID='${req.body.change_id}'`,(err,data)=>{
						if(err){
							console.error(err)
							res.status(500).send('database err').end()
						}else{
							res.redirect('/admin/banner')
						}
					})
			}else{
				db.query(`insert into banner_table (title, description, href) value('${title}', '${description}', '${href}')`, (err,data) => {
					if(err){
						res.status(500).send('database err').end()
					}else{
						res.redirect('/admin/banner')
					}
				})
			}

			
		}
	})
	return router
}

